//
//  String.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 common. All rights reserved.
//

import Foundation
extension String {
    public func substring(_ index: Int) -> String {
        if self.count > index {
            let startIndex = self.index(self.startIndex, offsetBy: index)
            let subString = self[startIndex..<self.endIndex]
            
            return String(subString)
        } else {
            return self
        }
    }
    
    func cy_widthForComment(fontSize: CGFloat, height: CGFloat = 15) -> CGFloat {
        let font = UIFont.systemFont(ofSize: fontSize)
        let attributes = [
            NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):  font
            ] as [NSAttributedStringKey : Any]
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        return ceil(rect.width)
    }
    
    func cy_heightForComment(fontSize: CGFloat, width: CGFloat) -> CGFloat {
        let font = UIFont.systemFont(ofSize: fontSize)
        let attributes = [
            NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue):  font
            ] as [NSAttributedStringKey : Any]
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
        return ceil(rect.height)
    }
    
    
    func range(range : Range<String.Index>) -> NSRange? {
        let utf16view = self.utf16
        guard
            let from = String.UTF16View.Index(range.lowerBound, within: utf16view),
            let to = String.UTF16View.Index(range.upperBound, within: utf16view)
            else { return nil }
        let utf16Offset = utf16view.startIndex.encodedOffset
        let toOffset = to.encodedOffset
        let fromOffset = from.encodedOffset
        return NSMakeRange(fromOffset - utf16Offset, toOffset - fromOffset)
    }
    
    //Range转换为NSRange
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location,
                                     limitedBy: utf16.endIndex),
            let to16 = utf16.index(from16, offsetBy: nsRange.length,
                                   limitedBy: utf16.endIndex),
            let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self)
            else { return nil }
        return from ..< to
    }

    mutating func changePhoneNumber() -> String {
        if self.ch_length < 8 {
            return self
        }
        let string = (self as NSString).replacingCharacters(in: NSMakeRange(3, 4), with: "****") as String
        return string
    }
    
    func changeEmail() -> String {
        if self.ch_length < 6 {
            return self
        }
        let string = (self as NSString).replacingCharacters(in: NSMakeRange(2, 3), with: "***") as String
        return string
    }
    
    /// 校验密码格式
    ///
    /// - Parameter pass: 密码
    /// - Returns: 回调
    func judgePassWordLegal() -> Bool{
        var result = false
        if self.ch_length >= 8 {
            let regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$"
            let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
            result = predicate.evaluate(with: self)
        }
        return result
    }
    
    
    /// 校验邮箱格式
    ///
    /// - Returns: 结果
    func judgeEmail() -> Bool {
        var result = false
        let regex = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        result = predicate.evaluate(with: self)
        return result
    }
    
    
    /// 身份证格式校验
    ///
    /// - Returns: 返回
    func jusdgeIdenty() -> Bool {
        let regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$"
        let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return predicate.evaluate(with: self)
    }
    
    
    func isTrueIDNumber() -> Bool{
        
        var value = self
        
        value = value.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        
        var length : Int = 0
        
        length = value.characters.count
        
        if length != 15 && length != 18{
            //不满足15位和18位，即身份证错误
            return false
        }
        
        // 省份代码
        let areasArray = ["11","12", "13","14", "15","21", "22","23", "31","32", "33","34", "35","36", "37","41", "42","43", "44","45", "46","50", "51","52", "53","54", "61","62", "63","64", "65","71", "81","82", "91"]
        
        // 检测省份身份行政区代码
        let index = value.index(value.startIndex, offsetBy: 2)
        let valueStart2 = value.substring(to: index)
        
        //标识省份代码是否正确
        var areaFlag = false
        
        for areaCode in areasArray {
            
            if areaCode == valueStart2 {
                areaFlag = true
                break
            }
        }
        
        if !areaFlag {
            return false
        }
        
        var regularExpression : NSRegularExpression?
        
        var numberofMatch : Int?
        
        var year = 0
        
        switch length {
        case 15:
            
            //获取年份对应的数字
            let valueNSStr = value as NSString
            
            let yearStr = valueNSStr.substring(with: NSRange.init(location: 6, length: 2)) as NSString
            
            year = yearStr.integerValue + 1900
            
            if year % 4 == 0 || (year % 100 == 0 && year % 4 == 0) {
                //创建正则表达式 NSRegularExpressionCaseInsensitive：不区分字母大小写的模式
                //测试出生日期的合法性
                regularExpression = try! NSRegularExpression.init(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$", options: NSRegularExpression.Options.caseInsensitive)
            }else{
                
                //测试出生日期的合法性
                regularExpression = try! NSRegularExpression.init(pattern: "^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$", options: NSRegularExpression.Options.caseInsensitive)
            }
            
            numberofMatch = regularExpression?.numberOfMatches(in: value, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSRange.init(location: 0, length: value.characters.count))
            
            if numberofMatch! > 0 {
                return true
            }else{
                
                return false
            }
            
        case 18:
            
            let valueNSStr = value as NSString
            
            let yearStr = valueNSStr.substring(with: NSRange.init(location: 6, length: 4)) as NSString
            
            year = yearStr.integerValue
            
            if year % 4 == 0 || (year % 100 == 0 && year % 4 == 0) {
                
                //测试出生日期的合法性
                regularExpression = try! NSRegularExpression.init(pattern: "^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$", options: NSRegularExpression.Options.caseInsensitive)
                
            }else{
                
                //测试出生日期的合法性
                regularExpression = try! NSRegularExpression.init(pattern: "^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}(((19|20)\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|((19|20)\\d{2}(0[13578]|1[02])31)|((19|20)\\d{2}02(0[1-9]|1\\d|2[0-8]))|((19|20)([13579][26]|[2468][048]|0[048])0229))\\d{3}(\\d|X|x)?$", options: NSRegularExpression.Options.caseInsensitive)
            }
            
            numberofMatch = regularExpression?.numberOfMatches(in: value, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSRange.init(location: 0, length: value.characters.count))
            
            print("numberofMatch=========\(String(describing: numberofMatch))")
            
            if numberofMatch! > 0 {
                
                let a = getStringByRangeIntValue(Str: valueNSStr, location: 0, length: 1) * 7
                
                let b = getStringByRangeIntValue(Str: valueNSStr, location: 10, length: 1) * 7
                
                let c = getStringByRangeIntValue(Str: valueNSStr, location: 1, length: 1) * 9
                
                let d = getStringByRangeIntValue(Str: valueNSStr, location: 11, length: 1) * 9
                
                let e = getStringByRangeIntValue(Str: valueNSStr, location: 2, length: 1) * 10
                
                let f = getStringByRangeIntValue(Str: valueNSStr, location: 12, length: 1) * 10
                
                let g = getStringByRangeIntValue(Str: valueNSStr, location: 3, length: 1) * 5
                
                let h = getStringByRangeIntValue(Str: valueNSStr, location: 13, length: 1) * 5
                
                let i = getStringByRangeIntValue(Str: valueNSStr, location: 4, length: 1) * 8
                
                let j = getStringByRangeIntValue(Str: valueNSStr, location: 14, length: 1) * 8
                
                let k = getStringByRangeIntValue(Str: valueNSStr, location: 5, length: 1) * 4
                
                let l = getStringByRangeIntValue(Str: valueNSStr, location: 15, length: 1) * 4
                
                let m = getStringByRangeIntValue(Str: valueNSStr, location: 6, length: 1) * 2
                
                let n = getStringByRangeIntValue(Str: valueNSStr, location: 16, length: 1) * 2
                
                let o = getStringByRangeIntValue(Str: valueNSStr, location: 7, length: 1) * 1
                
                let p = getStringByRangeIntValue(Str: valueNSStr, location: 8, length: 1) * 6
                
                let q = getStringByRangeIntValue(Str: valueNSStr, location: 9, length: 1) * 3
                
                let S = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q
                
                print("S============\(S)")
                
                let Y = S % 11
                
                print("Y========\(Y)")
                
                var M = "F"
                
                let JYM = "10X98765432"
                
                M = (JYM as NSString).substring(with: NSRange.init(location: Y, length: 1))
                
                let lastStr = valueNSStr.substring(with: NSRange.init(location: 17, length: 1))
                
                if lastStr == "x" {
                    if M == "X" {
                        return true
                    }else{
                        
                        return false
                    }
                }else{
                    
                    if M == lastStr {
                        return true
                    }else{
                        
                        return false
                    }
                }
            }else{
                
                return false
            }
            
        default:
            return false
        }
    }
    
    func getStringByRangeIntValue(Str : NSString,location : Int, length : Int) -> Int{
        
        let a = Str.substring(with: NSRange(location: location, length: length))
        
        let intValue = (a as NSString).integerValue
        
        return intValue
    }
    
    var containsEmoji: Bool {
        
        for scalar in unicodeScalars {
            switch scalar.value {
            case
            0x00A0...0x00AF,
            0x2030...0x204F,
            0x2120...0x213F,
            0x2190...0x21AF,
            0x2310...0x329F,
            0x1F000...0x1F9CF:
                return true
            default:
                continue
            }
        }
        return false
    }

    func disable_emoji(str:String)->String{
        let regex = try!NSRegularExpression.init(pattern: "[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]", options: .caseInsensitive)
        
        let modifiedString = regex.stringByReplacingMatches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: str.characters.count), withTemplate: "")
        return modifiedString
    }
    
    ///删除前后空格
    func deleteBoundaryBlank() -> String {
        let str = self.trimmingCharacters(in: .whitespacesAndNewlines)
        return str
    }
}

extension String: ToJsonObject {
    func toData() -> Data? {
        return self.data(using: .utf8)
    }
}
